package com.hx.order.web;

import com.alibaba.fastjson.JSON;
import com.hx.common.R;
import com.hx.common.api.OrderService;
import com.hx.common.common.SnowflakeIdWorker;
import com.hx.common.domain.MiaoshaOrder;
import com.hx.common.domain.MqLog;
import com.hx.common.domain.OrderInfo;
import com.hx.common.to.OrderMessageTo;
import com.hx.order.dao.MqLogDao;
import com.hx.order.dao.OrderDao;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.UUID;

/**
 * @Author wonghiu
 * @Date 2021/6/4 21:05
 * @Version 1.0.1
 */
@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private MqLogDao mqLogDao;


    @GetMapping("/check")
    @ResponseBody
    public R check(@RequestParam("orderId") Long orderId) {
        OrderInfo miaoshaOrder = orderService.getOrderById(orderId);
        if (miaoshaOrder != null) {
            return R.ok().put("data", miaoshaOrder);
        }
        return R.error("查询失败");
    }

    @GetMapping("/test/createOrder")
    @ResponseBody
    // 测试消息队列的异步性能
    public R createOrderTest(@RequestParam("orderId") Long orderId) {
        OrderMessageTo miaoshaOrder = new OrderMessageTo();
        miaoshaOrder.setUserId(18912341266L);
        miaoshaOrder.setGoodsId(1L);
        miaoshaOrder.setOrderId(new Random().nextLong());

        // 记录消息日志，确保消息的可靠性
        MqLog mqLog = new MqLog();
        mqLog.setClassType(MiaoshaOrder.class.getTypeName());
        mqLog.setContent(JSON.toJSONString(miaoshaOrder));
        mqLog.setExchange("order-event-exchange");
        mqLog.setRoutingKey("order.miaosha.order");
        // 消息发送前状态为0
        mqLog.setState(0);
        mqLogDao.insert(mqLog);

        // 通过消息队列异步执行订单任务
        rabbitTemplate.convertAndSend("order-event-exchange","order.miaosha.order",miaoshaOrder,new CorrelationData(String.valueOf(mqLog.getId())));

//        orderService.createMiaoShaOrder(miaoshaOrder);
//        orderService.lockStock(miaoshaOrder);

        // 消息发送后状态为1，表示成功发送
        mqLog.setState(1);
        mqLogDao.update(mqLog);
        return R.ok();
    }
}
